package live.job;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class TouchIndexCache implements Job {

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		// TODO Auto-generated method stub
		
		
		String fileUrl = this.getClass().getClassLoader().getResource("").getPath();
    	
		File file = new File(fileUrl);
    	String rootUrl = returnRootUrl(file);
    	
    	String htmlContent = "";
		try {
			URL url = new URL("http://tuan.yofogo.com");
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.connect();
			InputStream inputStream = urlConnection.getInputStream();

			byte bytes[] = new byte[1024 * 2000];

			int index = 0;

			int count = inputStream.read(bytes, index, 1024 * 2000);

			while (count != -1) {

			index += count;

			count = inputStream.read(bytes, index, 1);

			}

			htmlContent = new String(bytes, "UTF-8");
			htmlContent = htmlContent.replace("charset=UTF-8", "charset=GB2312");
			urlConnection.disconnect();
			FileWriter fw = new FileWriter(rootUrl+"/index.html");
			fw.write(new StringBuffer(htmlContent.trim())
			.append("<br/><!--<br/>")
			.append("update time ").append(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()))
			.append("-->")
			.toString());
			fw.flush();
			fw.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String returnRootUrl(File file){
		String rootUrl = "";
		rootUrl=file.getParentFile().getPath();
		if(!file.getParentFile().getPath().endsWith("WebRoot")){
			rootUrl=returnRootUrl(file.getParentFile());
		}
		return rootUrl;
	}
	
}
